/* Copyright (C) 2007-2008  klevgert  http://code.google.com/p/db4o-netbeans/

This file is part of the db4o-netbeans module suite.

db4o-netbeans is free software; you can redistribute it and/or modify it under
the terms of version 2 of the GNU General Public License as published
by the Free Software Foundation and as clarified by db4objects' GPL 
interpretation policy, available at
http://www.db4o.com/about/company/legalpolicies/gplinterpretation/
Alternatively you can write to db4objects, Inc., 1900 S Norfolk Street,
Suite 350, San Mateo, CA 94403, USA.

db4o-netbeans is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. */

package com.db4o.nb.editor.nodes;

import com.db4o.ObjectContainer;
import com.db4o.nb.editor.dialogs.SelectTypeDialog;
import com.db4o.nb.editor.nodes.DatabaseNode.DatabaseNodeChildren;
import com.db4o.nb.util.ClassLoaderUtil;
import com.db4o.nb.util.DialogUtil;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import org.openide.actions.PropertiesAction;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import org.openide.util.actions.SystemAction;

/**
 *
 * @author klevgert
 */
public class CollectionNode extends AbstractNode {
  
  static final String ICON_PATH = "com/db4o/nb/editor/resources/field.gif";

  private Collection collection;
  private ObjectContainer objectContainer;
  
  /** Creates a new instance of CollectionNode */
  public CollectionNode(Collection collection, ObjectContainer oc) {
    super(new CollectionNodeChildren(collection, oc));
    
    this.collection = collection;
    this.objectContainer = oc;
    
    this.setDisplayName(collection.getClass().getName() + " #"+ collection.size());
    this.setIconBaseWithExtension(ICON_PATH);
  }

  /**
   * Gets all action that can be performed on this node.
   * @return Array of actions.
   */
  public Action[] getActions(boolean b) {
    
    Action[] actions = new Action[] {
      new AddObjectAction(),
      null,
      SystemAction.get(PropertiesAction.class)      
    };
    
    return actions;
  }  

   // <editor-fold defaultstate="collapsed" desc=" Actions ">                          
 
  /**
   * Action to add objects to the database. 
   */
  private class AddObjectAction extends AbstractAction {
    
    public AddObjectAction() {
      String name = NbBundle.getMessage(this.getClass(), "AddObject");
      this.putValue(NAME,name);
    }
    
    public void actionPerformed(ActionEvent e) {
      
      SelectTypeDialog std = new SelectTypeDialog(new JFrame(),true);
      std.setObjectContainer(CollectionNode.this.objectContainer);
      std.setVisible(true);

      if( std.getReturnStatus() == SelectTypeDialog.RET_OK) {

        String type = std.getSelectedClass();
        if( type.length() > 0 ) {
          
          try {

            Class clazz = ClassLoaderUtil.getClassLoader().loadClass(type);
            Object inst = clazz.newInstance();
            CollectionNode.this.objectContainer.set(inst);
            
            if( CollectionNode.this.collection == null ) {
              CollectionNode.this.collection = new ArrayList();
            }
            CollectionNode.this.collection.add(inst);

            CollectionNode.this.setChildren( 
                new CollectionNodeChildren(collection, CollectionNode.this.objectContainer)  
            );

          } catch (Exception ex) {
            
            String errmsg = NbBundle.getMessage(this.getClass(), "CannotCreateObject", ((ex!=null)? ex.toString(): "") );
            DialogUtil.showErrorMessage(errmsg);
          }
        }
      }
      
 //     DialogDescriptor dd = new DialogDescriptor( std , title);
      
    }
  }
  // </editor-fold >                          
  

// <editor-fold defaultstate="collapsed" desc=" Children ">                          
  
  public static class CollectionNodeChildren  extends Children.Keys {

    private Collection collection;
    private ObjectContainer objectContainer;

    /** Creates a new instance of Db4oQueryNodeChildren */
    public CollectionNodeChildren(Collection col, ObjectContainer oc) {
      this.collection = col;
      this.objectContainer = oc;
    }

    protected Node[] createNodes(Object object) {
      
      long oid = this.objectContainer.ext().getID(object);
      Node result = new ObjectNode(oid, this.objectContainer);
      return new Node[] {result};
    }

    protected void addNotify() {

      Object[] objects = new Object[collection.size()];
      int i=0;
      
      Iterator iter = collection.iterator();
      while( iter.hasNext() ) {
        objects[i++] = iter.next();
      }
      
      setKeys( objects );
    }

  }
    
// </editor-fold>                          
  
}
